# -*- coding: utf-8 -*-
# @Time : 2021/1/15 10:44
# @Author : geyeu
# @Site : 
# @File : clientClass.py
# @Software: PyCharm
import json
from clients.models import Summary
from clients.models import EveryDayIncome
from django.db.models.aggregates import Count, Sum
from datetime import datetime


def format_claim_datas(summary_values):
    # 索赔信息
    result = {
        'total_claim_cnt': 0,
        'claim_successful_cnt': 0,
        'claiming_cnt': 0,
        'claim_failed_cnt': 0

    }
    return result


def format_authorized_datas(summary_values):
    # 店铺授权信息
    result = {'total_store_cnt': 0, 'authorized_store_cnt': 0, 'unauthorized_store_cnt': 0}
    if summary_values:
        # 授权店铺数
        result['total_store_cnt'] = summary_values['authorize_success'] + summary_values['authorize_ing'] + summary_values[
            'authorize_failed']
        # # 已授权店铺数
        result['authorized_store_cnt'] = summary_values['authorize_success']
        # # 未授权店铺数
        result['unauthorized_store_cnt'] = summary_values['authorize_ing'] + summary_values['authorize_failed']
    return result


def format_categories_datas(summary_values, limit=1):
    """
    类目显示数据处理
    :param categories_item:
    :return:
    """
    result = [[] for _ in range(3)]

    # 显示类目
    categories_item = ['damaged_lost', 'delivery_acceptance_diff', 'refund_not_returned', 'exchange_not_returned',
                       'exchange_and_refund', 'overcharge_shipping', 'overcharge_storage_fees']
    if summary_values:
        total_num = summary_values['total_num']  # 总数量
        other = summary_values['other']  # 其它数量
        dispaly_info = []
        field_name_dic = {field.name: field.verbose_name for field in Summary._meta.fields}
        categories_item_name = {k: v for k, v in field_name_dic.items() if k in categories_item}
        categories_info = [{'field': k, 'name': v, 'values': summary_values[k]} for k, v in categories_item_name.items()]
        if total_num > 0:
            for item in categories_info:
                if item['values'] > 0:
                    percent = item['values'] / total_num * 100
                    if percent >= limit:
                        tmp_dic = dict()
                        tmp_dic['name'] = item['name']
                        tmp_dic['values'] = item['values']
                        tmp_dic['percent'] = int(percent * 100) / 100
                        dispaly_info.append(tmp_dic)
                    else:
                        other += item['values']
                else:
                    pass
            dispaly_info = sorted(dispaly_info, key=lambda e: e.__getitem__('values'), reverse=True)
            # 如果其它类型的数目之和超过limit则显示
            other_percent = other / total_num * 100
            if other_percent >= limit:
                dispaly_info.append({'name': '其它', 'values': other, 'percent': int(other_percent * 100) / 100})
            for item in dispaly_info:
                result[0].append(item['name'])
                result[1].append(item['values'])
                result[2].append(item['percent'])
            result.append([100 for _ in range(len(dispaly_info))])
        else:
            pass
    return {'categories_cnt': json.dumps(result)}


def format_income_datas(userid):
    current_year = datetime.now().year
    current_month = datetime.now().month
    current_day = datetime.now().day

    def format_every_year_income():
        """
        # 年收入概览和今年收入处理函数
        返回最近两年的收入列表以及今年的总收入
        :return: [['2020', '2021'], [1583.34, 7561.47]], 7561.47
        """
        every_year_income = list(EveryDayIncome.objects.filter(userid__exact=userid).values('yy').annotate(annual_income=Sum('day_income')))
        # every_year_incom: [{'yy': '2020', 'annual_income': Decimal('1583.34')}, {'yy': '2021', 'annual_income': Decimal('7561.47')}]

        year_income_format = []  # 返回参数1，最近两年的收入列表
        current_year_income = 0.0  # 返回参数2, 今年的总收入

        if every_year_income:
            year_str = []  # 年份
            year_income = []  # 年份对应的收入
            for year_dic in every_year_income[-2:]:
                year_str.append(year_dic['yy'])
                year_income.append(float(year_dic['annual_income']))
                if year_dic['yy'] == str(current_year):
                    current_year_income = float(year_dic['annual_income'])
            year_income_format.append(year_str)
            year_income_format.append(year_income)
        return year_income_format, current_year_income

    def format_every_month_income():
        """
        # 月收入概览和本月收入
        # 返回1月到本月的收入列表和本月收入
        :return:
        """

        every_month_income = list(EveryDayIncome.objects.filter(userid__exact=userid, yy__exact=str(current_year)).values('mm').annotate(annual_income=Sum('day_income')))
        every_month_income = {month['mm']: float(month['annual_income']) for month in every_month_income}   # {'2': 725.93, '3': 6835.54}

        month_income_format = []  # 返回参数1， 每月收入列表
        current_month_income = 0.00  # 返回参数2, 本月收入

        for month in range(1, current_month+1):
            income = every_month_income.get(str(month), 0.00)
            month_income_format.append(income)
            if month == current_month:
                current_month_income = income

        return month_income_format, current_month_income

    def format_every_day_income():
        """
        每天收入概览和今天收入
        :return:
        """
        every_day_income = list(EveryDayIncome.objects.filter(userid__exact=userid, yy__exact=str(current_year), mm__exact=str(current_month)).values('dd').annotate(
                annual_income=Sum('day_income')))
        every_day_income = {day['dd']: float(day['annual_income']) for day in every_day_income}

        day_income_format = []  # 返回参数1， 每月收入列表
        current_day_income = 0.00  # 返回参数2, 本月收入
        for day in range(1, current_day + 1):
            income = every_day_income.get(str(day), 0.00)
            day_income_format.append(income)
            if day == current_day:
                current_day_income = income
        return day_income_format, current_day_income


    # 总收入
    total_income = EveryDayIncome.objects.filter(userid__exact=userid).aggregate(total_income=Sum('day_income'))
    # 年收入概览和今年收入
    every_year_income, current_year_income = format_every_year_income()
    # 本年月收入概览和本月收入
    every_month_income, current_month_income = format_every_month_income()
    # 本月收入概览和今天收入
    every_day_income, current_day_income = format_every_day_income()

    annual_income_summary = json.dumps([
                {"value": 20, "name": "损坏丢失"},
                {"value": 26, "name": "发货接收差异"},
                {"value": 24, "name": "退款未退货"},
                {"value": 25, "name": "换货未退款"},
                {"value": 20, "name": "换货且多退款"},
                {"value": 25, "name": "多收运费"},
                {"value": 30, "name": "多收存储费"}
            ])  # 年收入分布汇总
    total_income_summary = json.dumps(every_year_income)  # 总收入汇总,展示最近两年收入概览

    # 收入信息
    result = {
        'daily_income': current_day_income, 'monthly_income': current_month_income, 'annual_income': current_year_income, 'total_income': total_income['total_income'] or 0,
        'daily_income_summary': every_day_income, 'monthly_income_summary': every_month_income,
        'annual_income_summary': annual_income_summary, 'total_income_summary': total_income_summary
    }
    return result


class Client():
    def __init__(self, user):
        self.user = user

    def get_home_info(self):
        summary_values = Summary.objects.filter(userid=self.user.id).values()
        if summary_values:
            summary_values = summary_values[0]
        else:
            summary_values = []
        # 索赔信息
        claim_datas = format_claim_datas(summary_values)
        # 店铺授权信息
        store_datas = format_authorized_datas(summary_values)
        # 收入信息
        income_datas = format_income_datas(self.user.id)
        # 类目
        categories_datas = format_categories_datas(summary_values)

        homeinfo = dict()
        info = [claim_datas, store_datas, income_datas, categories_datas]
        for item in info:
            homeinfo.update(item)
        return homeinfo
        # homeinfo = {
        #     "total_claim_cnt": 100,  # 索赔总数
        #     "claim_successful_cnt": 100,  # 索赔成功数
        #     "claiming_cnt": 100,  # 索赔中数
        #     "claim_failed_cnt": 100,  # 索赔失败数
        #     "total_store_cnt": 100,  # 店铺总数
        #     "authorized_store_cnt": 100,  # 已授权店铺数
        #     "unauthorized_store_cnt": 100,  # 未授权店铺数
        #     "daily_income": 100,  # 今日收入
        #     "monthly_income": 100,  # 本月收入
        #     "annual_income": 100,  # 今年收入
        #     "total_income": 100,  # 总收入
        #     "daily_income_summary": [
        #         30, 0, 30, 0, 30, 0, 30, 60, 20, 40,
        #     ],  # 日收入汇总
        #     "monthly_income_summary": [
        #         24, 40, 101, 134, 90, 230, 210, 230,
        #     ],  # 月收入汇总
        #     "annual_income_summary": json.dumps([
        #         {"value": 20, "name": "损坏丢失"},
        #         {"value": 26, "name": "发货接收差异"},
        #         {"value": 24, "name": "退款未退货"},
        #         {"value": 25, "name": "换货未退款"},
        #         {"value": 20, "name": "换货且多退款"},
        #         {"value": 25, "name": "多收运费"},
        #         {"value": 30, "name": "多收存储费"}
        #     ]),  # 年收入分布汇总
        #     "total_income_summary": json.dumps([
        #         ["2020", "2021", "2022"],  # 年份
        #         [200, 300, 0]  # 对应的值
        #     ]),  # 总收入汇总
        #     "categories_cnt": json.dumps([
        #         ["损坏丢失", "发货接收差异", "退款未退货", "换货未退款", "换货且多退款", "多收运费"],  # 类目名称
        #         [793, 793, 702, 664, 664, 610],  # 各类目数量
        #         [17, 17, 15, 14, 14, 13],  # 各类目所占百分数
        #         [100, 100, 100, 100, 100, 100],
        #     ]) # 各类目占比
        # }
